package com.ssm.service;

import com.hqj.ReturnUtil;
import com.ssm.dao.UserDao;
import com.ssm.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceI implements BaseService<User> {

    @Autowired
    private UserDao ud;
    @Resource(name="menuServiceI")
    private MenuServiceI msi;

    public User get(User user) {
        List<User> list = this.find(user);
        return list.size()>0?list.get(0):null;
    }

    public List<User> find(User user) {
        return ud.find(user);
    }

    public Map<String,Object> add(User user) {
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        int i = ud.add(user);
        return ReturnUtil.returnMap(i>0,"新增");
    }

    public Map<String,Object> edit(User user) {
        user.setUpdateTime(new Date());
        int i = ud.edit(user);
        return ReturnUtil.returnMap(i>0,"编辑");
    }

    public Map<String,Object> remove(User user) {
        int i = ud.remove(user.getId());
        return ReturnUtil.returnMap(i>0,"删除");
    }

    public Map<String,Object>login(User user, HttpSession session){
        Map<String,Object> map = new HashMap<String, Object>();
        //先验证验证码是否正确
        String code = (String)session.getAttribute("code");
        //销毁验证码
        session.removeAttribute("code");
        if(user.getCode()==null||!user.getCode().equalsIgnoreCase(code)){
            map.put("is",false);
            map.put("msg","验证码错误");
            return map;
        }

        String password = user.getPassword();
        user = this.get(user);
        if(user==null){
            map.put("is",false);
            map.put("msg","登录名错误!");
        }else{
            if(user.getPassword().equals(password)){
                user.setPassword(null);
                //把登录成功的信息存入到session
                session.setAttribute("user",user);

                Map<String,List<String>> btnMap = msi.getBtnByRoleId(user.getRoleId());
                session.setAttribute("btnMap",btnMap);

                map.put("is",true);
                map.put("msg","登录成功!");
            }else{
                map.put("is",false);
                map.put("msg","密码错误!");
            }
        }

        return map;
    }
}
